﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using IHISCETeim.BLL;
using IHISCETeim.Library;
using IHISCETeim.Model;
using System.Data;
using System.Text;

namespace IHISCETeim.Web.MachineSys.MacModel
{
    public partial class OCompleteMacNGReportPage : PageBase
    {
        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.查看 };
            }
        }
        protected override string DWZRef
        {
            get
            {
                return "OCompleteMacNGReport";
            }
        }

        protected int Year
        {
            get
            {
                return GetRequestValue<int>("year", DateTime.Now.Year);
            }
        }
        protected int Month
        {
            get
            {
                return GetRequestValue<int>("Month", DateTime.Now.Month);
            }
        }
        /// <summary>
        /// 当前要显示的问题分析月份 格式为2011-07
        /// </summary>
        protected string CurrShowMonth
        {
            get
            {
                return Year.ToString() + "-" + Month.ToString();
            }
        }

        /// <summary>
        /// 报表要开始显示的月份,上半年还是下半年
        /// </summary>
        protected int StateMonth
        {
            get
            {
                if (Month <= 6)
                    return 1;
                else
                    return 7;
            }
        }
        /// <summary>
        /// 报表要结速显示的月份,上半年还是下半年
        /// </summary>
        protected int EndMonth
        {
            get
            {
                return StateMonth + 5;
            }
        }



        protected string GetYearList()
        {
            string liTemplete = "<option value='{0}' {1}>{0}年</option>";
            string rHtml = "";
            int nowYear = DateTime.Now.Year;
            for (int i = (nowYear - 3); i <= nowYear; i++)
            {
                rHtml = rHtml + string.Format(liTemplete, i, i == Year ? "selected" : "");
            }
            return rHtml;
        }

        #region 相关方法
        /// <summary>
        /// 获取报表1相关数据
        /// </summary>
        /// <param name="tYear"></param>
        /// <param name="tMoneth"></param>
        /// <returns>
        /// 只返回一行
        /// 列AllCount表示所有的性能检测台数
        /// 列NGCount表示有出现问题记录的台数
        /// 列NotNGCount表示未出现问题的台数
        /// 列FPY表示合格率(NotNGCount/AllCount)
        /// </returns>
        protected DataRow OInspection_GetReport1(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));

            return OInspectionController.OInspection_GetReport1(statedate, enddate).Rows[0];
        }
        /// <summary>
        /// 获取报表2相关数据
        /// </summary>
        /// <param name="tYear"></param>
        /// <param name="tMoneth"></param>
        /// <returns>
        /// 只返回一行
        /// 列AllCount表示所有的出入库检查台数
        /// 列NGCount表示有出现问题记录的台数
        /// 列NotNGCount表示未出现问题的台数
        /// 列FPY表示合格率(NotNGCount/AllCount)
        /// </returns>
        protected DataRow OInspection_GetReport2(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));

            return OInspectionController.OInspection_GetReport2(statedate, enddate).Rows[0];
        }
        /// <summary>
        /// 获取指定时间段内机型
        /// </summary>
        /// <param name="tYear"></param>
        /// <param name="tMoneth"></param>
        /// <returns></returns>
        protected List<string> GetReportMacType3(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
            DataTable DT = OInspectionController.OInspection_GetReportMacType3(statedate, enddate);
            List<string> lisCol = new List<string>();
            foreach (DataRow dr in DT.Rows)
            {
                lisCol.Add(dr["MachineType"].ToString());
            }
            if (lisCol.Count <= 0)
            {
                lisCol.Add("55NSL");
                lisCol.Add("65NS");
                lisCol.Add("80NS");
            }
            return lisCol;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="ItemType"></param>
        /// <param name="colLabel">colLabel格式为 2011-07,55NSL</param>
        /// <returns></returns>
        protected object OInspection_GetReport3(string ItemType, string colLabel)
        {
            string[] cols = colLabel.Split(new char[] { ',' });
            DateTime statedate = Convert.ToDateTime(cols[0] + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
            string macType = cols[1];
            return OInspectionController.OInspection_GetReport3(macType, ItemType, statedate, enddate);

        }

        protected DataTable OInspection_GetReport4(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));

            return OInspectionController.OInspection_GetReport4(statedate, enddate);
        }

        protected DataTable OInspection_GetReport5(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));

            return OInspectionController.OInspection_GetReport5(statedate, enddate);
        }

        protected DataTable OInspection_GetReport6(object tYear, object tMoneth)
        {
            DateTime statedate = Convert.ToDateTime(tYear.ToString() + "-" + tMoneth.ToString() + "-01 00:00:00");
            DateTime enddate = Convert.ToDateTime(statedate.AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));

            return OInspectionController.OInspection_GetReport6(statedate, enddate);
        }
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 绑定性能检测合格
        /// </summary>
        protected string BindReport1Dat()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("月份", typeof(string));
            dt.Columns.Add("百分比", typeof(decimal));
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                DataRow dr = dt.NewRow();
                dr["月份"] = string.Format("{0}月", sindex);
                dr["百分比"] = Convert.ToDecimal(Convert.ToDecimal(OInspection_GetReport1(Year, sindex)["FPY"]).ToString("F1"));
                //dt.Columns.Add(string.Format("{0}年{1}月", Year, sindex), typeof(string));
                dt.Rows.Add(dr);
            }

            JsonSerializerHelper json = new JsonSerializerHelper();
            return  json.Serialize(dt);
        }
        
        protected string BindReport2Dat()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("月份", typeof(string));
            dt.Columns.Add("百分比", typeof(decimal));
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                DataRow dr = dt.NewRow();
                dr["月份"] = string.Format("{0}月", sindex);
                dr["百分比"] = Convert.ToDecimal(Convert.ToDecimal(OInspection_GetReport2(Year, sindex)["FPY"]).ToString("F1"));
                //dt.Columns.Add(string.Format("{0}年{1}月", Year, sindex), typeof(string));
                dt.Rows.Add(dr);
            }

            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(dt);
        }

        #region 二.各机型不良率
        /// <summary>
        /// 获取报表3的数据json
        /// </summary>
        /// <returns></returns>
        protected string GetReport3FiledData()
        {
            StringBuilder sb = new StringBuilder();            
            //表头添加
            sb.Append("[");
            sb.Append("'项目',");
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                List<string> colNames = GetReportMacType3(Year, sindex);
                if (colNames.Count > 0)
                {
                    colNames.Add("合计");                    
                }
                foreach (string itm in colNames)
                {
                    sb.AppendFormat("'{0}{1}{2}',", Year, sindex,itm);
                }
            }
            sb.Append("]");

            string filedstr = sb.ToString();
            int lastpos = filedstr.LastIndexOf(",");
            filedstr = filedstr.Remove(lastpos, 1);

            return filedstr;
        }

        protected string GetReport3Data()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("项目", typeof(string));
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                List<string> colNames = GetReportMacType3(Year, sindex);
                if (colNames.Count > 0)
                {
                    colNames.Add("合计");
                }
                foreach (string itm in colNames)
                {
                    dt.Columns.Add(string.Format("{0}{1}{2}", Year, sindex, itm), typeof(string));
                }
            }
            string[] items = new string[] {"性能检测台数", "性能检测品异台数", "性能检测不良率", "出入库检查台数", "出入库检查品异台数", "出入库不良率" };
            foreach (string itemtype in items)
            {
                DataRow dr = dt.NewRow();
                if (itemtype == "机型")
                {
                    dr["项目"] = itemtype;
                    for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
                    {
                        List<string> colNames = GetReportMacType3(Year, sindex);
                        if (colNames.Count > 0)
                        {
                            colNames.Add("合计");
                        }
                        foreach (string itm in colNames)
                        {
                            dr[string.Format("{0}{1}{2}", Year, sindex, itm)] = itm;
                        }
                    }
                    dt.Rows.Add(dr);

                }
                else
                {
                    dr["项目"] = itemtype;
                    for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
                    {
                        List<string> colNames = GetReportMacType3(Year, sindex);
                        if (colNames.Count > 0)
                        {
                            colNames.Add("合计");
                        }
                        foreach (string itm in colNames)
                        {
                            object x = OInspection_GetReport3(itemtype, Year.ToString() + "-" + sindex.ToString() + "," + itm);
                            object showx = 0;
                            if (itemtype == "性能检测不良率" || itemtype == "出入库不良率")
                                showx = Convert.ToDecimal(x).ToString("F2") + "%";
                            else
                                showx = x;

                            dr[string.Format("{0}{1}{2}", Year, sindex, itm)] = showx;
                        }
                    }
                    dt.Rows.Add(dr);
                }                
            }

            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(dt);

        }


        protected string GetReport3ColumnJs()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("[");
            sb.Append(@"{
                text: '项目  月份',
                columns: [{
                    text     : '机型',
                    width    : 100,
                    sortable : false,
                    dataIndex: '项目'
                }]},");
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                sb.Append(@"{");
                sb.AppendFormat(@"text:'{0}月',", sindex);
                sb.Append(@"columns: [");

                List<string> colNames = GetReportMacType3(Year, sindex);
                if (colNames.Count > 0)
                {
                    colNames.Add("合计");
                }
                int lastag = 0;
                foreach (string itm in colNames)
                {
                    lastag++;
                    sb.Append(@"{");
                    sb.AppendFormat(@"text     : '{0}',
                        width    : 75,
                        sortable : false,
                        dataIndex: '{1}'"
                        ,
                        itm,
                        string.Format("{0}{1}{2}", Year, sindex, itm)
                     );
                    //dr[string.Format("{0}{1}{2}", Year, sindex, itm)] = OInspection_GetReport3(itemtype, Year.ToString() + "-" + sindex.ToString() + "," + itm);
                   // sb.Append(@"},");

                    sb.Append(@"}");
                  
                    if (lastag != colNames.Count())
                    {
                        sb.Append(@",");
                    }

                }


                sb.Append(@"]");
                sb.Append("},");
                
            }
            sb.Append("]");
            string filedstr = sb.ToString();
            int lastpos = filedstr.LastIndexOf(",");
            filedstr = filedstr.Remove(lastpos, 1);

            
            return filedstr;
        }


        protected string GetReport3LineDataFiled(bool isaxesfiled)
        {
            StringBuilder sb = new StringBuilder();
            //表头添加
            sb.Append("[");
            if(!isaxesfiled)
                sb.Append("'月份',");
            List<string> colNames = new List<string>();
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                List<string> colNames_temp = GetReportMacType3(Year, sindex);

                foreach (string itm in colNames_temp)
                {
                    if (!colNames.Contains(itm))
                    {
                        colNames.Add(itm);
                    }
                }
            }
            foreach (string itm in colNames)
            {
                sb.AppendFormat("'{0}',", itm);
            }

            sb.Append("]");

            string filedstr = sb.ToString();
            int lastpos = filedstr.LastIndexOf(",");
            filedstr = filedstr.Remove(lastpos, 1);

            return filedstr;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="itemType">性能检测不良率 或 出入库不良率</param>
        /// <returns></returns>
        protected string GetReport3LineDat(string itemType)
        {
           // string[] items = new string[] { "性能检测台数", "性能检测品异台数", "性能检测不良率", "出入库检查台数", "出入库检查品异台数", "出入库不良率" };
            DataTable dt = new DataTable();
            dt.Columns.Add("月份", typeof(string));

            List<string> colNames = new List<string>();
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                List<string> colNames_temp = GetReportMacType3(Year, sindex);

                foreach (string itm in colNames_temp)
                {
                    if (!colNames.Contains(itm))
                    {
                        colNames.Add(itm);
                    }
                }
            }
            foreach (string itm in colNames)
            {
                dt.Columns.Add(itm, typeof(decimal));
            }

            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                DataRow dr = dt.NewRow();
                dr["月份"]=string.Format("{0}月",sindex);
                foreach (string itm in colNames)
                {
                    dr[itm] = Convert.ToDecimal(Convert.ToDecimal(OInspection_GetReport3(itemType, Year.ToString() + "-" + sindex.ToString() + "," + itm)).ToString("f1"));
                   // dt.Columns.Add(itm, typeof(decimal));
                }
                dt.Rows.Add(dr);
            }
            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(dt);
            //return "";
        }

        protected string GetReport3LineSeries()
        {
            StringBuilder sb = new StringBuilder();
            //表头添加
            sb.Append("[");            
            List<string> colNames = new List<string>();
            for (int sindex = StateMonth; sindex <= EndMonth; sindex++)
            {
                List<string> colNames_temp = GetReportMacType3(Year, sindex);

                foreach (string itm in colNames_temp)
                {
                    if (!colNames.Contains(itm))
                    {
                        colNames.Add(itm);
                    }
                }
            }

            foreach (string itm in colNames)
            {/*
              {
                                    type: 'line',
                                    xField: 'x',
                                    yField: [
                                        'y'
                                    ],
                                    smooth: 3
                                }
              */
                sb.AppendFormat(@"
                        {{
                            type: 'line',
                            xField: '月份',
                            yField: [
                                '{0}'
                            ],
                            smooth: 3,
                            label: {{
                                field: '{0}',
                                display: 'insideEnd',
                                'text-anchor': 'middle',
                                renderer: Ext.util.Format.numberRenderer('0.0%'),
                                orientation: 'vertical',
                                color: '#333'
                            }},
                            tips: {{
                              trackMouse: true,
                              width: 140,
                              height: 28,
                              renderer: function(storeItem, item) {{
                                 this.setTitle(storeItem.get('月份') + ': ' + storeItem.get('{0}') + ' %');
                              }}
                            }}
                        }},
                ", itm);
              
            }

            sb.Append("]");

            string filedstr = sb.ToString();
            int lastpos = filedstr.LastIndexOf(",");
            filedstr = filedstr.Remove(lastpos, 1);

            return filedstr;
        }
        #endregion

        protected string GetReport4Dat()
        {
            DataTable sDT = OInspection_GetReport4(Year, Month);
            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(sDT);
        }

        protected string GetReport5Dat()
        {
            DataTable sDT = OInspection_GetReport5(Year, Month);
            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(sDT);
        }
        protected string GetReport6Dat()
        {
            DataTable sDT = OInspection_GetReport6(Year, Month);
            JsonSerializerHelper json = new JsonSerializerHelper();
            return json.Serialize(sDT);
        }
    }
}